package com.xdan.memory.recieve;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xdan.memory.entity.LogMessage;
import com.xdan.memory.service.MatchUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author:
 * @since: 2023/9/8 14:44
 **/
@Component
@Slf4j
public class ReceiveLogMessage {

    @Resource
    private MatchUserService matchUserService;


    @RabbitListener(queues = "xdan.error.log")
    public void consumptionLog(Message message, Channel channel) {
        byte[] body = message.getBody();

        byte[] bytes = findNumber(body);

        String logMessage = new String(bytes);
//        logMessage = logMessage.replaceAll("\\n", "");

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LogMessage logMessageObject = objectMapper.readValue(logMessage, LogMessage.class);
            log.info("【消费数据】{}", logMessageObject.toString());
//            LogMessage logMessageObject = JSONUtil.toBean(quote, LogMessage.class);
//
//            Object level = message.getMessageProperties().getHeader("level");
//            Object categoryName = message.getMessageProperties().getHeader("categoryName");
            String location = message.getMessageProperties().getHeader("location");
//
//
            matchUserService.matchAndSendMessage(location, logMessageObject.getService(), logMessageObject.getMessage(), logMessageObject.getStack());

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private byte[] findNumber(byte[] body) {
        for (int i = 0; i < body.length; i++) {
            if (body[i] == 13 || body[i] == 9) {
                body[i] = 32;
            }
        }

        return body;
    }
}